package org.linlinjava.litemall.admin.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.db.domain.LitemallShop;
import org.linlinjava.litemall.db.domain.LumierePackage;
import org.linlinjava.litemall.db.dto.AdminShopSpecialDateDTO;
import org.linlinjava.litemall.db.service.LumierePackageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.List;

@Component
public class AdminPackageWeekJob{
    /**
     * 日志记录器
     */
    private final Log logger = LogFactory.getLog(AdminPackageWeekJob.class);

    @Autowired
    private LumierePackageService lumierePackageService;

    @Scheduled(cron = "0 0/1 * * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void erpPurchase() {
        List<LumierePackage> packageList = lumierePackageService.list();
        for (LumierePackage lumierePackage : packageList) {
            lumierePackage.setIsOnSale(packageCheckWeeksTime(lumierePackage));
            lumierePackageService.updateById(lumierePackage);
        }
    }

    private boolean packageCheckWeeksTime(LumierePackage lumierePackage){
        // 套餐的营业时间已经存在于 lumierePackage.getWeeksTime() 集合中
        List<LocalTime[]> weeksTime = lumierePackage.getWeeksTime();
        if(weeksTime==null|| CollUtil.isEmpty(weeksTime)){return false;}
        // 获取当前日期和时间
        LocalDate currentDate = LocalDate.now();
        LocalTime currentTime = LocalTime.now();
        // 获取当前是星期几
        DayOfWeek currentDayOfWeek = currentDate.getDayOfWeek();

        // 获取对应的门店营业时间
        LocalTime[] businessHours = weeksTime.get(currentDayOfWeek.getValue() - 1);

        // 判断当前时间是否处于门店的开业时间范围内
        boolean isOpen = currentTime.isAfter(businessHours[0]) && currentTime.isBefore(businessHours[1]);

        List<AdminShopSpecialDateDTO> specialDateList = lumierePackage.getSpecial(); // 假设您已经有了AdminShopSpecialDateDTO的集合
        LocalDate today = LocalDate.now();
        // 遍历集合中的每个AdminShopSpecialDateDTO对象
        for (AdminShopSpecialDateDTO dto : specialDateList) {
            LocalDate specialDate = dto.getSpecialDate();
            LocalTime[] specialTime = dto.getSpecialTime();

            // 在这里进行特定逻辑处理，判断门店是否营业
            // 判断specialDate是否是今天
            if (!specialDate.isEqual(today)) {
                continue;
            }
            // 判断当前时间是否在营业时间范围内
            isOpen = currentTime.isAfter(specialTime[0]) && currentTime.isBefore(specialTime[1]);
        }
        return isOpen;
    }

}
